import { FC, memo } from "react"
import { View, ViewStyle, TextStyle } from "react-native"

import { Text } from "@/components/Text"
import type { ChatMessage } from "@/services/api/types"
import { useAppTheme } from "@/theme/context"
import type { ThemedStyle } from "@/theme/types"

interface MessageItemProps {
  id: string
  role: ChatMessage["role"]
  content: string
  timestamp: Date
  style?: {
    container?: ThemedStyle<ViewStyle>
    bubble?: ThemedStyle<ViewStyle>
    text?: ThemedStyle<TextStyle>
    time?: ThemedStyle<TextStyle>
  }
}

/**
 * 消息项组件 - 用于渲染静态消息
 * 使用memo优化，只在props变化时重渲染
 */
export const MessageItem: FC<MessageItemProps> = memo(({ id, role, content, timestamp, style }) => {
  const { themed } = useAppTheme()
  const messageRole = role === "system" ? "assistant" : role

  return (
    <View style={themed(style?.container || $defaultMessageContainer(messageRole))}>
      <View style={themed(style?.bubble || $defaultMessageBubble(messageRole))}>
        <Text style={themed(style?.text || $defaultMessageText(messageRole))}>{content}</Text>
      </View>
      <Text style={themed(style?.time || $defaultMessageTime)}>
        {timestamp.toLocaleTimeString()}
      </Text>
    </View>
  )
})

// 设置displayName用于调试
MessageItem.displayName = "MessageItem"

// 默认样式
const $defaultMessageContainer =
  (role: "user" | "assistant"): ThemedStyle<ViewStyle> =>
  ({ spacing }) => ({
    marginBottom: spacing.sm,
    alignItems: role === "user" ? "flex-end" : "flex-start",
  })

const $defaultMessageBubble =
  (role: "user" | "assistant"): ThemedStyle<ViewStyle> =>
  ({ colors, spacing }) => ({
    maxWidth: "80%",
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    borderRadius: 16,
    backgroundColor: role === "user" ? colors.palette.neutral300 : colors.palette.neutral200,
    borderBottomRightRadius: role === "user" ? 4 : 16,
    borderBottomLeftRadius: role === "user" ? 16 : 4,
  })

const $defaultMessageText =
  (role: "user" | "assistant"): ThemedStyle<TextStyle> =>
  ({ colors }) => ({
    color: colors.text,
    fontSize: 16,
    lineHeight: 20,
  })

const $defaultMessageTime: ThemedStyle<TextStyle> = ({ colors, spacing }) => ({
  color: colors.textDim,
  fontSize: 12,
  marginTop: spacing.xs,
  textAlign: "center",
})

// 导出类型
export type { MessageItemProps }
